package xyz.bali16.module.sign.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Preconditions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import xyz.bali16.application.core.utils.TimeUtil;
import xyz.bali16.module.sign.entity.SignPoint;
import xyz.bali16.module.sign.entity.SignPoint;
import xyz.bali16.module.sign.mapper.SignPointMapper;
import xyz.bali16.module.sign.model.SignPointAddParam;
import xyz.bali16.module.sign.model.SignPointPageParam;
import xyz.bali16.module.sign.model.SignPointUpdateParam;
import xyz.bali16.module.sign.service.SignPointService;

/**
 * @author bali2 on 9/3/2023.
 * @version 1.0
 */
@Service
public class SignPointServiceImpl extends ServiceImpl<SignPointMapper, SignPoint> implements SignPointService {
    private final SignPointMapper signPointMapper;

    public SignPointServiceImpl(SignPointMapper signPointMapper) {
        this.signPointMapper = signPointMapper;
    }

    @Override
    public IPage<SignPoint> getPage(SignPointPageParam param) {
        IPage<?> page = new Page<>(param.getCurrent(), param.getSize());
        return this.baseMapper.getPage(page, param.getUserId(), param.getPoint());
    }

    @Override
    public void addSignPoint(SignPointAddParam param) throws Exception {
        Preconditions.checkNotNull(param, "SignPointAddParam 参数不能为为空");
        SignPoint sign = new SignPoint();
        BeanUtils.copyProperties(param, sign);
        System.out.println(sign);
        sign.setGmtModified(TimeUtil.getNowTimeToSeconds());
        Wrapper wrapper = Wrappers.<SignPoint>lambdaQuery().eq(SignPoint::getUserId,sign.getUserId());
        SignPoint existSignPoint = signPointMapper.selectOne(wrapper);
        if (existSignPoint == null) {
            save(sign);
        } else {
            existSignPoint.setPoint(existSignPoint.getPoint() + param.getPoint());
            updateById(existSignPoint);
        }
    }

    @Override
    public void updateSignPoint(SignPointUpdateParam param) throws Exception {
        Preconditions.checkNotNull(param, "SignPointAddParam 参数不能为为空");
        SignPoint sign = new SignPoint();
        BeanUtils.copyProperties(param, sign);
        sign.setGmtModified(TimeUtil.getNowTimeToSeconds());
        updateById(sign);
    }


    @Override
    public void delete(String signId) throws Exception {
        if (signId == null) {
            return;
        }
        removeById(signId);

    }
}
